const formatTime2 = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return [year, month, day].map(formatNumber).join('-');
};

const formatMonth = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  return [year, month].map(formatNumber).join('-');
};

const formatYear = date => {
  const year = date.getFullYear();
  return year;
};


const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

function encode(befre) {
  var now = "";
  var result = "";

  for (var i = 0; i < befre.length; i++) {
    if (i % 2 == 0) {
      result += befre[i].charCodeAt() + 2 + ",";
    } else {
      result += befre[i].charCodeAt() - 1 + ",";
    }

    if (i == befre.length - 1) {
      var res = new Array();
      res = result.split(",");

      for (var p = 0; p < res.length - 1; p++) {
        now += String.fromCharCode(res[p]);
      }
    }
  }

  return now;
}

function decode(befre) {
  var now = "";
  var result = "";

  for (var i = 0; i < befre.length; i++) {
    if (i % 2 == 0) {
      result += befre[i].charCodeAt() - 2 + ",";
    } else {
      result += befre[i].charCodeAt() + 1 + ",";
    }

    if (i == befre.length - 1) {
      var res = new Array();
      res = result.split(",");

      for (var p = 0; p < res.length - 1; p++) {
        now += String.fromCharCode(res[p]);
      }
    }
  }

  return now;
}

function rpxH() {
  var rpxHeight = 0;
  wx.getSystemInfo({
    success: function (res) {
      var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
      rpxHeight = clientHeight * rpxR;
    }
  });
  return rpxHeight;
}

function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500;
  }

  let _lastTime = null;
  return function () {
    let _nowTime = new Date();

    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments);
      _lastTime = _nowTime;
    }
  };
}

function getUID() { 
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

function isMobileNumber(phone) {
    var message = "";
    var myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+\d{8})$/;
    if (phone === '') {
        message = "手机号码不能为空！";
    } else if (phone.length != 11) {
        message = "请输入11位手机号码！";
    }  else if(!myreg.test(phone)){
        message = "请输入正确的手机号!";
    }
    return message;
}

function isCardID(sId){
 var iSum=0 ;
 let aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
 if(!/^\d{17}(\d|x)$/i.test(sId)) return "你输入的身份证长度或格式错误";
 sId=sId.replace(/x$/i,"a");
 if(aCity[parseInt(sId.substr(0,2))]==null) return "你的身份证地区非法";
 sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));
 var d=new Date(sBirthday.replace(/-/g,"/")) ;
 if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return "身份证上的出生日期非法";
 for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11) ;
 if(iSum%11!=1) return "你输入的身份证号非法";
 return "";
}

// 深度克隆 在框架 uview-ui/libs/function/index.js

function gettagvalue(as_str, as_key){
	var ls_str1 = ''
	var ls_str2 = ''
	var ls_rtn = ''
	var ll_pos1 = 0
	var ll_pos2 = 0
	
	ls_str1 = '[' + as_key + ']'
	ls_str2 = '[/' + as_key + ']'
	ll_pos1 = as_str.indexOf(ls_str1)
	ll_pos2 = as_str.indexOf(ls_str2)
	if(ll_pos2 == -1 || ll_pos2 === '') return ''
	ls_rtn = as_str.substring(ll_pos1+ls_str1.length, ll_pos2)
	
	return ls_rtn
}


function structureTreeData(data, menuid = "menuid", parentmenuid = "parentmenuid"){
	let parentmenuids = [];
	let menuids = [];
	data.forEach(item => {
		   if (!parentmenuids.includes(item.parentmenuid)) {
			   parentmenuids.push(item.parentmenuid);
		   }
		   if (!menuids.includes(item.menuid)) {
			   menuids.push(item.menuid);
		   }
	});
	//父节点数据
	let parents = data.filter(
		   value => !menuids.includes(value.parentmenuid)
	);
	//子节点数据
	let childrens = data.filter(
		   value => menuids.includes(value.parentmenuid)
	);
	//构造树形结构数据
	let structure = (parents, childrens) => {
		   //遍历父节点数据
		   parents.forEach(parent => {
			   //遍历子节点数据
			   childrens.forEach((children, index) => {
				   //此时找到父节点对应的一个子节点
				   if (children.parentmenuid === parent.menuid) {
					   //对子节点数据进行深拷贝
					   let newChildrens = JSON.parse(JSON.stringify(childrens));
					   //让当前子节点从newChildrens中移除，newChildrens作为新的子节点数据，
					   //这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
					   newChildrens.splice(index, 1);
					   //让当前子节点作为唯一的父节点，去递归查找其对应的子节点
					   structure([children], newChildrens);
					   //把找到子节点放入父节点的children属性中
					   typeof parent.children !== "undefined"
						   ? parent.children.push(children)
						   : (parent.children = [children]);
				   }
			   });
		   });
	};
	//调用构造方法
	structure(parents, childrens);
	return parents;
}


function structureTreeData2(data, dm = "dm", parentdm = "parentdm"){
	let parentdms = [];
	let dms = [];
	data.forEach(item => {
		   if (!parentdms.includes(item.parentdm)) {
			   parentdms.push(item.parentdm);
		   }
		   if (!dms.includes(item.dm)) {
			   dms.push(item.dm);
		   }
	});
	//父节点数据
	let parents = data.filter(
		   value => !dms.includes(value.parentdm)
	);
	//子节点数据
	let childrens = data.filter(
		   value => dms.includes(value.parentdm)
	);
	//构造树形结构数据
	let structure = (parents, childrens) => {
		   //遍历父节点数据
		   parents.forEach(parent => {
			   //遍历子节点数据
			   childrens.forEach((children, index) => {
				   //此时找到父节点对应的一个子节点
				   if (children.parentdm === parent.dm) {
					   //对子节点数据进行深拷贝
					   let newChildrens = this.deepClone(childrens);
					   //让当前子节点从newChildrens中移除，newChildrens作为新的子节点数据，
					   //这里是为了让递归时，子节点的遍历次数更少，如果父子关系的层级越多，越有利
					   newChildrens.splice(index, 1);
					   //让当前子节点作为唯一的父节点，去递归查找其对应的子节点
					   structure([children], newChildrens);
					   //把找到子节点放入父节点的children属性中
					   typeof parent.children !== "undefined"
						   ? parent.children.push(children)
						   : (parent.children = [children]);
				   }
			   });
		   });
	};
	//调用构造方法
	structure(parents, childrens);
	return parents;
}



function parseTree(list2,roleid,userid) {
	console.log(list2)
	var list = []
	for(var n=0; n<list2.length; n++){
		var item = list2[n]
		list.push(item)
		if(item.funname01 != ''){
			item['funname00'] = '查看'
			item['userid'] = userid
			item['roleid'] = roleid
			if(item.power ==1){
				item['fun00'] = '1'
			}else{
				item['fun00'] = '0'
			}
			for(var k=0; k<16; k++){
				var funname = ''
				var funnum = ''
				var fun = ''
				if(k>=9){
					funnum = '' + (k)
				}else{
					funnum = '0' + (k)
				}
				funname = 'funname' + funnum
				fun = 'fun' + funnum
				if(item[funname] != '' && item[funname] != undefined){
					var tempitem = {}
					tempitem['modcode'] = item.modcode + funnum
					tempitem['modname'] = item[funname]
					tempitem['modlevel'] = item.modlevel + 1
					tempitem['power'] = item[fun]
					tempitem['funname'] = item[funname]
					tempitem['mc'] = item.modcode + funnum + ' ' + item[funname]
					if(item[fun] == 1){
						tempitem['checked'] = true
					}else{
						tempitem['checked'] = false
					}
					list.push(tempitem)
				}
			}
		}
	}
	
	
	
	for(var m=0; m<list.length; m++){
		list[m]['id'] = (m+1) 
		list[m]['label'] = list[m].modname
		var modlevel = list[m].modlevel
		if(modlevel == 1){
			list[m]['parentId']= null
		}
		if(modlevel != 1){
			var modcode = list[m].modcode.substring(0, list[m].modcode.length-2)
			for(var j=0; j<list.length; j++){
				var modcode2 = list[j].modcode
				if(modcode2 == modcode){
					list[m]['parentId']= j+1
					continue
				}
			}
		}
	}
	console.log(list)
	let map = {}, node, tree = [], i;
	for (i = 0; i < list.length; i++) {
	  map[list[i].id] = i; // 初始化映射
	  list[i].children = []; // 初始化children数组
	}
	for (i = 0; i < list.length; i++) {
	  node = list[i];
	  if (node.parentId !== undefined && node.parentId !== null && node.parentId !== '') {
	    // 如果当前项有父ID，则找到父项的位置并将当前项添加到父项的children数组中
	    list[map[node.parentId]].children.push(node);
	  } else {
	    // 如果没有父ID，则为树的根节点
	    tree.push(node);
	  }
	}
	return tree;
}

//下面是一个通用较高的自定义日期时间格式化函数的示例：
function formatdatecustom(date, format) {
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
    a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
    A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      );
    }
  }
  return format;
}


// function formatDateCust(date, pattern) {
//   let map = {
//     'M': date.getMonth() + 1, // 月份
//     'MM': date.getMonth() + 1, // 月份
//     'MMM': date.toLocaleString('default', { month: 'short' }), // 月份缩写
//     'MMMM': date.toLocaleString('default', { month: 'long' }), // 月份全称
//     'y': date.getFullYear(), // 年份
//     'yy': date.getFullYear().toString().slice(-2), // 年份最后两位
//     'yyyy': date.getFullYear(), // 完整年份
//     'd': date.getDate() < 10 ? '0' + date.getDate() : date.getDate(), // 日
//     'dd': date.getDate() < 10 ? '0' + date.getDate() : date.getDate(), // 日
// 	'hh': date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),// 小时
// 	'mm': date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(), // 分
// 	'ss': date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(), // 秒
//   };
 
//   pattern = pattern.replace(/(yyyy|yy|y|MMMM|MMM|MM|M|dddd|ddd|dd|d|hh|mm|ss)/g, function(match) {
//     return map[match];
//   });
 
//   return pattern;
// }

function compare(version1,version2) {
  let arr1=version1.split(".");
  let arr2=version2.split(".");
  let length=Math.max(arr1.length,arr2.length);
  for (let i = 0; i < length; i++) {
    const n1 = Number(arr1[i]||0)
    const n2 = Number(arr2[i]||0)
    // version1 > version2 返回1，如果 version1 < version2 返回-1，不然返回0
    if (n1 > n2) return 1
    if (n1 < n2) return -1
  }
  return 0
}

function formatNumber2(num,pattern){
	if(typeof num === 'string') num = parseFloat(num)
    var strarr = num?num.toString().split('.'):['0'];
    var fmtarr = pattern?pattern.split('.'):[''];
    var retstr='';
    // 整数部分
    var str = strarr[0];
    var fmt = fmtarr[0];
    var i = str.length-1;
    var comma = false;
    for(var f=fmt.length-1;f>=0;f--){
        switch(fmt.substr(f,1)){
            case '$':
                retstr = '$' + retstr;
            break;
            case '#':
                if(i>=0 ) retstr = str.substr(i--,1) + retstr;
                break;
            case '0':
                if(i>=0) retstr = str.substr(i--,1) + retstr;
                else retstr = '0' + retstr;
            break;
            case ',':
                comma = true;
            break;
        }
    }
    if(i>=0){
        if(comma){
        var l = str.length;
        for(;i>=0;i--){
        retstr = str.substr(i,1) + retstr;
        if(i>0 && ((l-i)%3)==0) retstr = ',' + retstr;
        }
        }
        else retstr = str.substr(0,i+1) + retstr;
    }
    
    retstr = retstr+'.';
    // 处理小数部分
    str=strarr.length>1?strarr[1]:'';
    fmt=fmtarr.length>1?fmtarr[1]:'';
    i=0;
    for(var f=0;f<fmt.length;f++){
    switch(fmt.substr(f,1)){
        case '#':
        if(i<str.length) retstr+=str.substr(i++,1);
        break;
        case '0':
        if(i<str.length) retstr+= str.substr(i++,1);
        else retstr+='0';
        break;
    }
    }

    return retstr.replace(/^,+/,'').replace(/\.$/,'');
}

function translg(menuname,i18nArr){
	let temname = ''
	i18nArr.forEach((ival)=>{
		if(ival.original === menuname && ival.category != ''){
			temname = ival.translation
		}
	})
	if(temname==''){
		i18nArr.forEach((ival)=>{
			if(ival.original === menuname){
				temname = ival.translation
			}
		})
	}
	
	if(temname!=''){
		return temname
	}else{
		return menuname
	}
}



function isObject(obj) {
    return Object.keys(obj).length > 0;
}

module.exports = {
  formatTime2,
  formatMonth,
  formatYear,
  encode,
  decode,
  throttle,
  rpxH,
  getUID,
  isMobileNumber,
  isCardID,
  structureTreeData,
  structureTreeData2,
  gettagvalue,
  parseTree,
  formatdatecustom,
  compare,
  formatNumber2,
  translg,
  isObject
};